﻿
using Modbus.Data;
using Modbus.Device;
using Modbus.Utility;

using System.Net;
using System.Net.Http;
using System.Net.Sockets;

namespace CKS.AGV.Core
{
    public static class ModbusMainService
    {
       
        static byte slaveAddress = 1;//站号
        static bool ServerIsOK = false;


        static ModbusTcpSlave slave;
       static IModbusMaster master;
        public static void Start()
        {
            if(!ServerIsOK)
            {
               var listener = new TcpListener(IPAddress.Any, 502);
                listener.Start();
                slave = ModbusTcpSlave.CreateTcp(1, listener);
                slave.DataStore = DataStoreFactory.CreateDefaultDataStore();
                _ = slave.ListenAsync();




                ServerIsOK = true;
                //192.168.220.127

                // 创建 TCP 客户端并连接到 Modbus 从站
                TcpClient client = new TcpClient();
                client.Connect(IPAddress.Parse("127.0.0.1"), 502);
                // 创建 Modbus TCP 主站
                 master = ModbusIpMaster.CreateIp(client);

               
                // IPAddress ip = IPAddress.Parse("127.0.0.1");
                //client = new ModbusTcpClient(new IPEndPoint(ip, 502));
                //var res = client.Open();
                TestOP20_ushort(1,1); 
            }
        }




        public static void WriteUShort(int addr,ushort value)
        {
            //https://blog.csdn.net/wushangwei2019/article/details/136385859
            string hexString = $"0x{value.ToString("D4")}";
            // 去除 0x 前缀
            if (hexString.StartsWith("0x"))
            {
                hexString = hexString.Substring(2);
            }

            byte[] bytes = new byte[hexString.Length / 2];
            for (int i = 0; i < hexString.Length; i += 2)
            {
                bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
            }


            var hexParts = new string[2];
            hexParts[0] = bytes[0].ToString("D2");
            hexParts[1] = bytes[1].ToString("D2");
            string hex = string.Join(" ", hexParts);
            // var c = client.Write($"{addr}", bytes, slaveAddress);
            Array.Reverse(bytes);
            var tox = BitConverter.ToUInt16(bytes);
            master.WriteSingleRegister(slaveAddress,(ushort)addr,tox);
        }


        public static void TestOP20_ushort(int address, ushort value)
        {
            var bytes = SplitNumberToBytes(value);
            Array.Reverse(bytes);
            // var c  =client.Write($"{address}", bytes, slaveAddress);
            var tox  = BitConverter.ToUInt16(bytes);
            master.WriteSingleRegister(slaveAddress, (ushort)address, tox);
        }
        /// <summary>
        /// ushort 对应 word
        /// </summary>
        /// <param name="address"></param>
        /// <param name="value"></param>
        public static void WriteAgvWord(int address, ushort value)
        {
           
            string hexString = $"0x{value.ToString("D4")}";
            // 去除 0x 前缀
            if (hexString.StartsWith("0x"))
            {
                hexString = hexString.Substring(2);
            }

            byte[] bytes = new byte[hexString.Length / 2];
            for (int i = 0; i < hexString.Length; i += 2)
            {
                bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
            }


            var hexParts = new string[2];
            hexParts[0] = bytes[0].ToString("D2");
            hexParts[1] = bytes[1].ToString("D2");
            string hex = string.Join(" ",hexParts);
            // var c = client.Write($"{address}", bytes, slaveAddress);

            Array.Reverse(bytes);
            var tox = BitConverter.ToUInt16(bytes);
            master.WriteSingleRegister(slaveAddress, (ushort)address, tox);
        }

        //public static string GetSendTaskHex()
        //{
        //   var a =  client.ReadUInt16(1, stationNumber: stationNumber);
        //   var b = client.ReadUInt16(2, stationNumber: stationNumber);
        //   var c = client.ReadUInt16(3, stationNumber: stationNumber);
        //   var d = client.ReadUInt16(4, stationNumber: stationNumber);

        //    // 将每个 ushort 值转换为字节数组并拼接成十六进制字符串
        //    var hexParts = new string[8];

        //    var bytesA = BitConverter.GetBytes(a.Value);
        //    hexParts[0] = bytesA[1].ToString("X2");
        //    hexParts[1] = bytesA[0].ToString("X2");

        //    var bytesB = BitConverter.GetBytes(b.Value);
        //    hexParts[2] = bytesB[1].ToString("X2");
        //    hexParts[3] = bytesB[0].ToString("X2");

        //    var bytesC = BitConverter.GetBytes(c.Value);
        //    hexParts[4] = bytesC[1].ToString("X2");
        //    hexParts[5] = bytesC[0].ToString("X2");

        //    var bytesD = BitConverter.GetBytes(d.Value);
        //    hexParts[6] = bytesD[1].ToString("X2");
        //    hexParts[7] = bytesD[0].ToString("X2");

        //    // 拼接所有十六进制部分
        //    var hex = string.Join(" ", hexParts);
        //    return hex;
        //}

        public static string GetSendTaskHex()
        {
            try
            {
                var values = master.ReadHoldingRegisters(slaveAddress, (ushort)1, 5);

                var hexParts = new string[10];
                for (int i = 0; i < 5; i++)
                {
                   
                    var value = values[i];
                  
                    var bytes = BitConverter.GetBytes(value);
                    // 反转字节顺序以处理大小端问题
                    Array.Reverse(bytes);

                    hexParts[i * 2] = bytes[0].ToString("X2");
                    hexParts[i * 2 + 1] = bytes[1].ToString("X2");
                }
                var hex = string.Join(" ", hexParts);
                return hex;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"读取数据时发生错误: {ex.Message}");
                return null;
            }
        }


      

        public static  ushort ReadUShort(int address)
        {
          // var x =  client.ReadUInt16($"{address}",slaveAddress);
            return master.ReadHoldingRegisters(slaveAddress, (ushort)address, 1).First();

          //  return x.Value;
        }

      

        static byte[] SplitNumberToBytes(int number)
        {
            string numberStr = number.ToString("D4"); // 将数字转换为长度为 4 的字符串，不足 4 位前面补 0
            byte[] result = new byte[2];
            result[0] = byte.Parse(numberStr.Substring(0, 2));
            result[1] = byte.Parse(numberStr.Substring(2, 2));
            return result;
        }
    }
}
